<template>
  <div class="login-container">
    <div class="login-banner">
      <canvas id="login-banner" style="width: 100%; height: 100%; position: absolute" />
    </div>
    <div class="login-form">
      <div class="login-logo">
        <img src="../assets/logo.png" alt="">
        <span class="ml10">大闸蟹溯源系统</span>
      </div>
      <div v-show="!showReset && !showRegister">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="免密码登录" name="first" />
          <el-tab-pane label="密码登录" name="second" />
        </el-tabs>
        <el-form v-show="activeName === 'first'" ref="loginForm" :model="loginForm" :rules="loginRules" autocomplete="on" label-position="left">
          <el-form-item prop="username">
            <el-input
              ref="username"
              v-model="loginForm.username"
              placeholder="手机号"
              name="username"
              type="text"
            />
          </el-form-item>
          <el-form-item prop="validate">
            <el-input
              ref="username"
              v-model="loginForm.validate"
              placeholder="验证码"
              name="username"
              type="text"
              tabindex="1"
            />
            <el-link type="info" :underline="false" class="sms-code">获取验证码</el-link>
          </el-form-item>
          <el-button :loading="loading" type="primary" style="width:100%;" @click.native.prevent="handleLogin">登录</el-button>
          <p class="mt10 clearfix">
            <el-link type="primary" class="fl" @click="showRegister = true">去注册</el-link>
          <!-- <el-link v-show="activeName === 'second'" type="primary" class="fr">忘记密码?</el-link> -->
          </p>
        </el-form>
        <el-form v-show="activeName === 'second'" ref="loginForm2" :model="loginForm" :rules="loginRules" autocomplete="on" label-position="left">
          <el-form-item prop="username">
            <el-input
              ref="username"
              v-model="loginForm.username"
              placeholder="手机号"
              name="username"
              type="text"
            />
          </el-form-item>
          <el-form-item v-if="activeName === 'second'" prop="password">
            <el-input
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="密码"
              name="password"
              tabindex="2"
              @keyup.enter.native="handleLogin"
            />
            <!-- <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span> -->
          </el-form-item>
          <el-button :loading="loading" type="primary" style="width:100%;" @click.native.prevent="handleLogin">登录</el-button>
          <p class="mt10 clearfix">
            <el-link type="primary" class="fl" @click="showRegister = true">去注册</el-link>
            <el-link type="primary" class="fr" @click="showReset = true">忘记密码?</el-link>
          </p>
        </el-form>
      </div>
      <Reset v-if="showReset" @handle-back="backAction" />
      <Register v-if="showRegister" @handle-back="backAction" />
    </div>
  </div>
</template>

<script>
import Reset from '../components/ResetPwd'
import Register from '../components/Register'
// import { login } from '../api'

export default {
  name: 'Login',
  components: {
    Reset,
    Register
  },
  data () {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入用户名'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不得少于6位'))
      } else {
        callback()
      }
    }
    return {
      activeName: 'first',
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        validate: [{ required: true, trigger: 'blur', message: '请输入验证码' }]
      },
      passwordType: 'password',
      loading: false,
      redirect: undefined,
      otherQuery: {},
      showReset: false,
      showRegister: false
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created () {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted () {
    this.drawBackground()
  },
  destroyed () {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    handleClick () {

    },
    backAction (type) {
      if (type === 'register') {
        this.showRegister = false
      } else {
        this.showReset = false
      }
    },
    showPwd () {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin () {
      // let jsonData = {
      //   jsonrpc: '2.0',
      //   method: 'getTransactionByBlockNumberAndIndex',
      //   params: [1, '0x1', '0x0'],
      //   id: 1
      // }
      // login(jsonData).then((res) => {
      //   // if ((status == 200)) {
      //   console.log(res)
      //   // }
      // })
      let key = 'loginForm'
      if (this.activeName !== 'first') {
        key = 'loginForm2'
      }
      this.$refs[key].validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('app/initUser', this.loginForm.username)
          this.$router.push({ path: '/main' })
          this.loading = false
        } else {
          return false
        }
      })
    },
    getOtherQuery (query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    drawBanner () {
      const canvas = document.getElementById('login-banner')
      const ctx = canvas.getContext('2d')
      canvas.width = document.documentElement.clientWidth
      canvas.height = document.documentElement.clientHeight
      ctx.fillStyle = 'rgba(0, 0, 0, 0.3)'
      ctx.strokeStyle = 'rgba(0, 0, 0, 0.1)'
      ctx.lineWidth = 0.5
      const num = 50
      for (let i = 0; i < num; i += 1) {
        this.createBalls(ctx, canvas)
      }
      for (let i = 0; i < num; i += 1) {
        ctx.save()
        ctx.beginPath()
        ctx.arc(this.balls[i].x, this.balls[i].y, this.balls[i].r, 0, Math.PI * 2)
        ctx.fill()
        ctx.restore()
      }
      for (let i = 0; i < num; i += 1) {
        for (let j = i + 1; j < num; j += 1) {
          if (this.distance(this.balls[i], this.balls[j]) < 500) {
            ctx.beginPath()
            ctx.moveTo(this.balls[i].x, this.balls[i].y)
            ctx.lineTo(this.balls[j].x, this.balls[j].y)
            ctx.stroke()
          }
        }
      }
      for (let k = 0; k < num; k += 1) {
        this.balls[k].x += this.balls[k].vx
        this.balls[k].y += this.balls[k].vy

        if (this.balls[k].x - this.balls[k].r > canvas.width) {
          this.balls[k].x = 0 - this.balls[k].r
        }
        if (this.balls[k].x + this.balls[k].r < 0) {
          this.balls[k].x = canvas.width + this.balls[k].r
        }
        if (this.balls[k].y - this.balls[k].r > canvas.height) {
          this.balls[k].y = 0 - this.balls[k].r
        }
        if (this.balls[k].y + this.balls[k].r < 0) {
          this.balls[k].y = canvas.height + this.balls[k].r
        }
      }
    },
    createBalls (ctx, canvas) {
      const X = Math.random() * canvas.width
      const Y = Math.random() * canvas.height
      const R = (Math.random() * 15) + 0.01
      const VX = Math.random() * 0.5 * (Math.floor((Math.random() * 2) + 1) ** -1)
      const VY = Math.random() * 0.5 * (Math.floor((Math.random() * 2) + 1) ** -1)
      this.balls.push({
        x: X,
        y: Y,
        r: R,
        vx: VX,
        vy: VY
      })
    },
    distance (point1, point2) {
      return Math.sqrt(((point1.x - point2.x) ** 2) + ((point1.y - point2.y) ** 2))
    },
    drawBackground () {
      class Circle {
        constructor (x, y) {
          this.x = x
          this.y = y
          this.r = (Math.random() * 14) + 1
          this.mx = (Math.random() * 2) - 1
          this.my = (Math.random() * 2) - 1
        }

        drawCircle (context) {
          const ctx = context
          ctx.beginPath()
          ctx.arc(this.x, this.y, this.r, 0, 360)
          ctx.closePath()
          ctx.fillStyle = 'rgba(0, 0, 0, 0.1)'
          ctx.fill()
        }

        drawLine (context, _circle) {
          const dx = this.x - _circle.x
          const dy = this.y - _circle.y
          const d = Math.sqrt((dx * dx) + (dy * dy))
          const ctx = context
          if (d < 150) {
            ctx.beginPath()
            ctx.moveTo(this.x, this.y)// 起始点
            ctx.lineTo(_circle.x, _circle.y)// 终点
            ctx.closePath()
            ctx.strokeStyle = 'rgba(0, 0, 0, 0.05)'
            ctx.stroke()
          }
        }

        move (w, h) {
          this.mx = (this.x < w && this.x > 0) ? this.mx : (-this.mx)
          this.my = (this.y < h && this.y > 0) ? this.my : (-this.my)
          this.x += this.mx / 2
          this.y += this.my / 2
        }
      }
      class CurrentCircle extends Circle {
        // constructor(x, y) {
        //   super(x, y);
        // }
        drawCircle (context) {
          const ctx = context
          ctx.beginPath()
          this.r = (this.r < 14 && this.r > 1) ? this.r + ((Math.random() * 2) - 1) : 2
          ctx.arc(this.x, this.y, this.r, 0, 360)
          ctx.closePath()
          ctx.fillStyle = 'rgba(0, 0, 0, 0.05)'
          ctx.fill()
        }
      }

      window.requestAnimationFrame =
        window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame
      const canvas = document.getElementById('login-banner')
      const ctx = canvas.getContext('2d')
      canvas.width = canvas.offsetWidth
      canvas.height = canvas.offsetHeight
      const w = canvas.width
      const h = canvas.height
      const circles = []
      const currentCircle = new CurrentCircle(0, 0)
      const draw = () => {
        ctx.clearRect(0, 0, w, h)
        for (let i = 0; i < circles.length; i += 1) {
          circles[i].move(w, h)
          circles[i].drawCircle(ctx)
          for (let j = i + 1; j < circles.length; j += 1) {
            circles[i].drawLine(ctx, circles[j])
          }
        }
        if (currentCircle.x) {
          currentCircle.drawCircle(ctx)
          for (let k = 1; k < circles.length; k += 1) {
            currentCircle.drawLine(ctx, circles[k])
          }
        }
        requestAnimationFrame(draw)
      }

      const init = (num) => {
        for (let i = 0; i < num; i += 1) {
          circles.push(new Circle(Math.random() * w, Math.random() * h))
        }
        draw()
      }

      window.addEventListener('load', init(100))
      window.onmousemove = (e) => {
        const ev = e || window.event
        currentCircle.x = ev.clientX
        currentCircle.y = ev.clientY
      }
      window.onmouseout = () => {
        currentCircle.x = null
        currentCircle.y = null
      }
    }
  }
}
</script>

<style lang="scss">
$bg:#283443;
$light_gray:#333;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .sms-code {
    position: absolute;
    right: 10px;
    top: 0;
  }
  .el-input {
    display: inline-block;
    height: 47px;
    width: 100%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px;
      color: #333;
      height: 47px;
          border-bottom: 1px solid #ccc;
      // caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }
  .login-logo {
    text-align: center;
    height: 50px;
    line-height: 50px;
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    &> img, span {
      vertical-align: middle;
    }
  }
  .el-form-item {

    background: #fff;
    color: #454545;
  }
}
</style>

<style lang="scss">
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: rgba($color: #000, $alpha: .1);
  overflow: hidden;

  .login-form {
    position: absolute;
    width: 400px;
    max-width: 100%;
    padding: 20px  35px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    overflow: hidden;
    border-radius: 4px;
    background: #fff;
    z-index: 11;
  }
  .login-banner {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    background: rgba($color: #000, $alpha: .1);
    &> video {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      object-fit: fill;
      z-index: 1;
    }
    &:after {
      content: '';
      width: 100%;
      height: 100%;
      // background: rgba($color: #000000, $alpha: .5);
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1;
    }
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: #333;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
